const { Car } = require("../models/carModel")
const {
    uploadFiles,
    moveFiles,
    removeFiles
} = require("../utils/upload"); //图片上传需要

// 添加车辆
async function addCar(req, res) {
    try {
        const { userID, model, licensePlate, motorcycleType, seat, imgs, address, value, rent, status, } = req.body;
        console.log(userID);
        if (imgs) { //判断头像存在与否，存在将缓存区的图片放在图片路径中,且将缓存区的文件夹删除
            moveFiles({
                fromPath: "./public/temp",
                toPath: "./public/images",
                filename: imgs
            });
            removeFiles("./public/temp");
        }
        await Car.create({ userID, model, licensePlate, motorcycleType, seat, imgs, address, value, rent, status, })
        res.send({
            msg: "添加车辆成功",
            status: 1,
        })
    } catch (error) {
        res.send({
            msg: "添加车辆失败",
            status: 0,
            error: error
        })
    }

}


// 删除车辆
async function delCar(req, res) {
    const { _id } = req.body
    const data = await Car.deleteOne({ _id })
    if (data.deletedCount == 1) {
        res.send({
            msg: '删除成功',
            status: 1,
        })
    } else {
        res.send({
            msg: '删除失败',
            status: 0,
        })
    }
}

// 修改车辆
async function changeCar(req, res) {
    try {
        const { _id, userId, model, licensePlate, motorcycleType, seat, imgs, address, rating, rent, status, } = req.body
        const data = await Car.update({ _id }, { userId, model, licensePlate, motorcycleType, seat, imgs, address, rating, rent, status, })
        if (data.nModified == 1) {
            res.send({
                msg: "修改成功",
                data: data,
                status: 1,
            })
        }
    } catch (error) {
        res.send({
            msg: "修改失败",
            status: 0,
            error: error
        })
    }
}

// 查找所有车辆
async function findAllCar(req, res) {
    try {
        const { pageSize, currentPage, type = "" } = req.body;
        // 总条数
        const total = await Car.countDocuments();
        // 总页数
        const totalPages = Math.ceil(total / pageSize);
        const data = await Car
            .find()
            .limit(pageSize - 0)
            .skip((currentPage - 1) * pageSize)
            .populate("userID")
        res.send({
            status: 1,
            data: { total, totalPages, data, pageSize, currentPage },
            msg: '获取车辆信息成功'
        })


    } catch (error) {
        res.send({
            status: 0,
            msg: "无法找到车辆"
        })
    }
}

//添加功能：根据名称搜索车辆
async function searchCarByName(req, res) {
    try {
        const { searchInput = "" } = req.body
        const data = await Car.find({ model: { $regex: searchInput, $options: '$i' } }).populate("userID")
        res.send({
            status: 1,
            data,
            msg: "搜索车辆成功"
        })
    } catch (error) {
        res.send({
            status: 0,
            msg: "无法找到车辆"
        })
    }
}

// 通过ID查找车辆
async function findCarByID(req, res) {
    console.log('++++++++', req.body);
    try {
        const data = await Car.findById(req.body._id)
        res.send({
            status: 1,
            data: data,
            message: '获取车辆信息成功'
        })
    } catch (error) {
        res.send({
            status: 0,
            message: '获取车辆信息失败',
            data: data
        })
    }
}


//添加车辆图片
async function uploadImgs(req, res) {
    const images = uploadFiles({
        path: "./public/temp"
    }); //路径以app.js作为参考
    images(req, res, (err) => {
        if (err) {
            console.info("上传失败" + err)
        } else {
            res.send({
                status: 1,
                massage: "上传成功",
                data: req.files[0].filename //将图片的路径返回去
            })
        }
    })
}

// 点击修改车辆出租状态
async function clickChangeStatus(req, res) {
    try {
        const { _id, type } = req.body
        const data = await Car.updateOne({ _id }, { status: type == "未出租" ? "已出租" : "未出租" })
        console.log(data);
        if (data.nModified) {
            res.send({
                msg: "修改车辆出租状态成功",
                status: 1,
                data: data
            })
        }

    } catch (error) {
        res.send({
            msg: "修改车辆出租状态失败",
            status: 1,
            error: error
        })

    }
}

// 点击修改车辆审核状态
async function clickChangeVerify(req, res) {
    try {
        const { _id, type } = req.body
        console.log(req.body);
        console.log(_id, type, "1231");
        const data = await Car.updateOne({ _id }, { verify: type == "未审核" ? "已审核" : "未审核" })
        res.send({
            msg: "修改车辆审核状态成功",
            status: 1,
            data: data
        })

    } catch (error) {
        res.send({
            msg: "修改车辆审核状态失败",
            status: 1,
            error: error
        })

    }
}


module.exports = { uploadImgs, addCar, delCar, changeCar, findAllCar, findCarByID, clickChangeStatus, clickChangeVerify,searchCarByName }